package manageAbilitiesServlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.abilitiesSession.AbilitySessionRemote;

public class AddAbilityServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertNewAbility(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertNewAbility(request, response);
	}

	private void insertNewAbility(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = 0;
		String name;
		try {
			Context jndiCtx = new InitialContext();
			AbilitySessionRemote abilitySession = (AbilitySessionRemote) jndiCtx
					.lookup("Progetto/AbilitySession/remote");
			name = request.getParameter("name");
			// l'abilita' non e' replicata
			id = abilitySession.inserAbility(name,
					request.getParameter("description"));
			if (id == 0)
				request.getSession().setAttribute("result", "error");
			else
				request.getSession().setAttribute("result", "commit");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Errore nella servlet");
		}
		response.sendRedirect("/ProgettoWeb/ManageAbility.html");
	}
}
